﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using MySql.Data.MySqlClient;
using BBMS.DLL.Base;
using BBMS.FrontEnd.Constant;
using System.Security.Cryptography;

namespace BBMS.DLL.Forms.Sys
{
    public partial class frmDbParameter : Form
    {
        private string SecondEntropy = "@Hanoitown34;'5.2009";

        public frmDbParameter()
        {
            InitializeComponent();
        }

        private void frmDbParameter_Load(object sender, EventArgs e)
        {
            // Load connection string info from configuration file
            foreach (ConnectionStringSettings cnn in ConfigurationManager.ConnectionStrings)
            {
                if (cnn.Name.Contains(FixedCode.DB_NAME))
                {
                    ConnectionStringSettings current = cnn;
                    LoadConfigurationToUI(DPAPI.Decrypt(cnn.ConnectionString, SecondEntropy));
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            // Test connection
            ConnectionStringSettings cnn = getCnnStrFromUI();
            MySqlConnection cn = new MySqlConnection(cnn.ConnectionString);
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                cn.Open();
                if (cn.State.Equals(ConnectionState.Open))
                {
                    ConnectionStringSettings current = config.ConnectionStrings.ConnectionStrings[FixedCode.DB_NAME];
                    if (current != null)
                    {
                        // if existed, replace with the info from UI
                        config.ConnectionStrings.ConnectionStrings.Remove(FixedCode.DB_NAME);
                        config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(FixedCode.DB_NAME, DPAPI.Encrypt(cnn.ConnectionString, SecondEntropy)));
                        //MessageBox.Show(Encoding.Unicode.GetString(encrypted));
                    }
                    else
                        // if does not existed, add new
                        config.ConnectionStrings.ConnectionStrings.Add(cnn);
                }
                // load to memory
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("ConnectionStrings");

                SystemHelper.DialogInfo("Done!");
            }
            catch (Exception ex)
            {
                SystemHelper.DialogExclamation("Test fail: " + ex.Message);
            }
            finally
            {
                cn.Close();
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            // Test connectivity
            ConnectionStringSettings cnn = getCnnStrFromUI();
            MySqlConnection cn = new MySqlConnection(cnn.ConnectionString);
            try
            {
                cn.Open();
                if (cn.State.Equals(ConnectionState.Open))
                    SystemHelper.DialogInfo("Test success!");
                else
                    SystemHelper.DialogExclamation("Test fail!");
            }
            catch (Exception ex)
            {
                SystemHelper.DialogExclamation("Test fail: " + ex.Message);
            }
            finally
            {
                cn.Close();
            }

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void chkDbName_CheckedChanged(object sender, EventArgs e)
        {
            // Set default db name
            txtDbName.Text = FixedCode.DB_NAME;
        }

        /// <summary>
        /// Create a connection string based on provided params
        /// </summary>
        /// <param name="name"></param>
        /// <param name="server"></param>
        /// <param name="port"></param>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <param name="dbname"></param>
        /// <returns></returns>
        private ConnectionStringSettings createConnectionString(string name, string server, string port, string user, string pass, string dbname)
        {
            string cnn = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};Persist Security Info=True;", server, port, dbname, user, pass);
            return new ConnectionStringSettings(name, cnn);
        }

        /// <summary>
        /// Create a connection string setting from provided information on UI
        /// </summary>
        /// <returns>connection string setting just created</returns>
        private ConnectionStringSettings getCnnStrFromUI()
        {
            return new ConnectionStringSettings(FixedCode.DB_NAME,
                                                string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};",
                                                                txtServerName.Text,
                                                                txtPort.Text,
                                                                txtDbName.Text,
                                                                txtUserName.Text,
                                                                txtPassword.Text));
        }

        /// <summary>
        /// Load a connection string to user interface for view/edit
        /// </summary>
        /// <param name="cnn">connection string setting to load</param>
        private void LoadConfigurationToUI(string cnn)
        {
            string[] param = cnn.Split(';');
            txtServerName.Text = param[0].Split('=').GetValue(1).ToString();
            txtPort.Text = param[1].Split('=').GetValue(1).ToString();
            txtDbName.Text = param[2].Split('=').GetValue(1).ToString();
            txtUserName.Text = param[3].Split('=').GetValue(1).ToString();
            txtPassword.Text = param[4].Split('=').GetValue(1).ToString();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.CheckState.Equals(CheckState.Checked))
            {
                txtDbName.Text = FixedCode.DB_NAME;
                txtDbName.ReadOnly = true;
            }
            else
            {
                txtDbName.Text = string.Empty;
                txtDbName.ReadOnly = false;
            }
        }
    }
}
